class PostsController < ApplicationController
    before_action :logged_in_user, only: :create
    before_action :correct_user, only: :destroy
    before_action :admin_user, only: :destroy
    def new
        @post = Post.new
    end
    def create
        @tagn=params[:ntag]
        @post = current_user.posts.build(post_params)
        if Tag.find_by(Title:@tagn)
            @post.tag_id = Tag.find_by(Title: @tagn).id
        else
            tag = Tag.create(Title: @tagn)
            tag.save
            tagid = tag.id
            @post.tag_id = tagid
        end
        if @post.save
            flash[:success] = "文章已发布"
            redirect_to root_url
        else
            flash[:fail] = @post.errors.full_messages.first.to_str
            redirect_to newpost_url
        end
    end
    def destroy
        Post.find(params[:id]).destroy
        flash[:success] = "已删除文章"
        redirect_to root_url
    end
    def show
        @post = Post.find(params[:id])
    end
    def edit
        @post = Post.find(params[:id])
    end
    def update
        @post = Post.find(params[:id])
        if @post.update(post_edit_params)
            flash[:success] = "文章编辑成功"
            redirect_to root_url
        else
            flash[:fail] = @post.errors.full_messages.first.to_str
            render 'edit'
        end
    end
    private
    def post_params
        params.require(:post).permit(:title,:content,:content_html,:tag_id)
    end
    def post_edit_params
        params.require(:post).permit(:title,:content,:content_html)
    end
    def logged_in_user
        unless logged_in?
          flash[:fail] = "权限不足"
          redirect_to login_url
        end
      end
    def correct_user
        @user = User.find(params[:id])
        redirect_to(root_url) and flash[:fail] = "权限不足" unless current_user?(@user)
    end
    
end
